import React, { useState, useEffect } from 'react';
import { Tag } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { connect, Dispatch } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import ProCard from '@ant-design/pro-card';
import { APP_INIT, APP_LIST, APP_ADD, APP_UPDATE, APP_UNMOUNT } from '@/actions/app';
import AGrid, { AGridButtonCallBackModel } from '@/components/SelfComp/AGrid';
import { ConnectState } from '@/models/connect';
import { AppItem } from '@/types/app';
import { DataItem, FlagEnum } from '@/types/global';
import { getItemValue } from '@/utils/commons';
import AddAppModal from './components/AddAppModal';
import AppQueryForm from './components/AppQueryForm';
import UpdateAppModal from './components/UpdateAppModal';

interface AppListProps {
  dispatch: Dispatch;
  appList: AppItem[],
  total: number,
  loading: boolean;
  pageSize: number;
  addLoading: boolean;
  updateLoading: boolean;
  systemData: DataItem[];
  clusterData: DataItem[];
  statusData: DataItem[];
}

const EMPTY: AppItem = {
  appId: '',
  systemCode: '',
  systemName: '',
  appCode: '',
  appName: '',
  manager: '',
  cluster: '',
  status: ''
}

/**
 * 应用管理，管理项目中的系统应用，以便职责分明
 */
const AppList: React.FC<AppListProps> = (props) => {
  // 新增弹窗
  const [addModalVisible, setAddModalVisible] = useState<boolean>(false);
  const [appFormData, setAppFormData] = useState<AppItem>(EMPTY);
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const [selectedRows, setSelectedRows] = useState<AppItem[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [queryParam, setQueryParam] = useState<AppItem>();
  // 默认为10
  const [pageSize, setPageSize] = useState<number>(10);
  const [flag, setFlag] = useState<FlagEnum>('edit');

  useEffect(() => {
    console.info('AppList.useEffect');
    // 查询本页面需所有参数
    const { dispatch } = props;
    dispatch(APP_INIT({}));
    return () => {
      dispatch(APP_UNMOUNT({}));
    }
  }, []);

  const columns: ColumnsType<AppItem> = [
    {
      title: '系统编码',
      dataIndex: 'systemCode',
      // width: 150
    },
    {
      title: '所在集群',
      dataIndex: 'cluster',
      // width: 70
    },
    {
      title: '应用编码',
      dataIndex: 'appCode',
      // width: 150
    },
    {
      title: '应用名称',
      dataIndex: 'appName',
      // width: 150
    },
    {
      title: '负责人',
      dataIndex: 'manager',
      // width: 70
    },
    {
      title: '状态',
      dataIndex: 'status',
      // width: 70
      render: (text: string, record: AppItem, index: number) => statusFunc(record),
    }
  ];

  const statusFunc = (record: AppItem) => {
    const { statusData } = props;
    const { status } = record;
    if (!status) {
      return '';
    }
    const value = getItemValue(statusData, status);
    if (status === '1') {
      return <Tag color='error'>{value}</Tag>;
    }
    return <Tag color='processing'>{value}</Tag>
  }

  /**
   * 查询满足条件的数据字典
   */
    const handleSubmitEx = (record: AppItem) => {
    console.info('AppList.handleSubmitEx');
    console.info(record);
    const queryParam = {
      ...record
    };
    // 查询条件保存起来，方便点击页码时使用
    // setState回调方法，保证先更新state
    setQueryParam(queryParam);
    fetchAllApp(1, pageSize, queryParam);
  }

  const handleReset = () => {
    // 是否清空表格
  }

  const openAddAppModal = () => {
    setAddModalVisible(true);
  }

  const handleAddModalOk = async (record: AppItem) => {
    // console.log(record);
    const { dispatch } = props;
    // console.info(dispatch);
    const res = await dispatch(APP_ADD(record));
    console.info(res);
    if (res) {
      setAddModalVisible(false);
      fetchAllApp(1, pageSize, queryParam);
    }
  }

  const handleAddModalCancel = () => {
    setAddModalVisible(false);
  };

  const openUpdateAppModal = (record: AppItem[], flag: FlagEnum) => {
    // 表格选中内容
    // console.info('openUpdateAppModal');
    // console.info(record);
    const row = record[0];
    const appFormData = {
      ...row,
    };
    setAppFormData(appFormData);
    setFlag(flag);
    setUpdateModalVisible(true);
  }

  /**
   * 更新面板的确定事件
   * @param {*} record 更新表单
   */
  const handleUpdateModalOk = async (record: AppItem) => {
    // console.log('handleUpdateModalOk');
    // console.log(record);
    // console.info(appFormData);
    if (flag === 'edit') {
      const { dispatch } = props;
      const res = await dispatch(APP_UPDATE(record));
      console.info(res);
      if (res) {
        setAppFormData(EMPTY);
        setUpdateModalVisible(false);
        fetchAllApp(1, pageSize, queryParam);
      }
    } else {
      setAppFormData(EMPTY);
      setUpdateModalVisible(false);
    }
  }

  const handleUpdateModalCancel = () => {
    setAppFormData(EMPTY);
    setUpdateModalVisible(false);
  };

  /**
   * 分页查询系统参数信息
   * @param {*} pageNum 页码
   * @param {*} pageSize 每页记录条数
   */
  const fetchAllApp = (pageNum: number, pageSize: number, queryParam?: AppItem) => {
    const { dispatch } = props;
    dispatch(APP_LIST({
      ...queryParam,
      pageSize,
      pageNum
    }));
  }

  /**
   * 处理按钮点击回调事件
   * @param {*} payload 数据包
   */
  const handleBtnCallBack = (callBackModel: AGridButtonCallBackModel<AppItem>) => {
    console.log('handleBtnCallBack');
    console.log(callBackModel);
    // btn 按钮
    // keys 表格勾选数组
    const { code } = callBackModel;
    // 新增
    if (code === 'add') {
      openAddAppModal();
      return;
    }
    // 修改
    if (code === 'edit') {
      const { rows } = callBackModel;
      openUpdateAppModal(rows, 'edit');
      return;
    }
    // 删除
    if (code === 'delete') {
      // const { rows } = callBackModel;
      // 调用删除服务，删除勾选数据
      return;
    }
    // 查看
    if (code === 'view') {
      const { rows } = callBackModel;
      openUpdateAppModal(rows, 'view');
      return;
    }
  }

  /**
   * 表格勾选回调函数
   * @param {*} rows 表格选中数据集合
   */
  const onSelectRow = (keys: React.Key[], rows: AppItem[]) => {
    setSelectedRowKeys(keys);
    setSelectedRows(rows);
  };

  /**
   * 页码改变的回调，参数是改变后的页码及每页条数
   * @param page 改变后的页码，上送服务器端
   * @param pageSize 每页数据条数
   */
  const onPageNumAndSizeChange = (page: number, pageSize: number) => {
    // console.log(page, pageSize);
    setPageSize(pageSize);
    fetchAllApp(page, pageSize);
  };

  const code = 'app-list';
  const { appList, loading, total, addLoading, updateLoading, systemData, clusterData, statusData } = props;
  // console.log(appList);
  // console.log(pageSize);
  const rowKey = (record: AppItem) => record.appId;
  const pkField = 'appId';

  return (
    <PageContainer>
      <ProCard title="系统应用查询" headerBordered>
        <AppQueryForm
          colon={false}
          loading={loading}
          onSubmit={handleSubmitEx}
          onReset={handleReset}
        />
        <AGrid
          code={code}
          btnCallBack={handleBtnCallBack}
          columns={columns}
          rowKey={rowKey}
          pkField={pkField}
          dataSource={appList}
          total={total}
          loading={loading}
          onSelectRow={onSelectRow}
          onPageNumAndSizeChange={onPageNumAndSizeChange}
          actionColumnFixed={'right'}
        />
      </ProCard>
      {
        !addModalVisible ? null :
        <AddAppModal
          systemData={systemData}
          clusterData={clusterData}
          statusData={statusData}
          colon={false}
          modalTitle='新增系统应用'
          modalWidth={1000}
          modalVisible={addModalVisible}
          loading={addLoading}
          onHandlerOK={handleAddModalOk}
          onHandlerCancel={handleAddModalCancel}
        />
      }
      {
        !updateModalVisible ? null :
        <UpdateAppModal
          systemData={systemData}
          clusterData={clusterData}
          statusData={statusData}
          colon={false}
          modalTitle=''
          modalWidth={1000}
          modalVisible={updateModalVisible}
          flag={flag}
          loading={updateLoading}
          formData={appFormData}
          onHandlerOK={handleUpdateModalOk}
          onHandlerCancel={handleUpdateModalCancel}
        />
      }
    </PageContainer>
  );
}

export default connect(({ apps: { rows, ...res }, loading }: ConnectState) => ({
  ...res,
  appList: rows,
  // 当用户 dispatch 对应 effect 时，dva 会自动注入对应 effect 的 loading 状态
  loading: loading.effects['apps/fetchAllApp'],
  addLoading: loading.effects['apps/addApp'],
  updateLoading: loading.effects['apps/updateApp'],
}))(AppList);